﻿using log4net;
using SuperFx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace SuperMoney.AdPlatformCallback.Controllers
{
	/// <summary>
	/// 磨盘广告回掉控制器。
	/// </summary>
    public class IMoPanController : Controller
    {
		/*****************************************************************
		 * 磨盘一个账户只能配置一个回调地址；
		 * param0是自定义参数，由应用传回来；
		 * param0中存储的数据格式：x1,x2,x3...；
		 * x1代表Super设备号，x2代表Android或iOS，x3代表磨盘应用编号
		 *****************************************************************/

		const string secret_key = "";
		const string adPlatform = "imopan";

		//
		// GET: /imopan/activate

		/// <summary>
		/// 应用激活
		/// </summary>
		/// <param name="id">广告编号</param>
		/// <param name="trand_no">交易流水号</param>
		/// <param name="imei">广告商返回设备编号</param>
		/// <param name="cash">用户获得的积分</param>
		/// <param name="param0">自定义参数，具体看头部备注</param>
		/// <param name="sign">签名</param>
		/// <returns></returns>
		public ActionResult Activate(string id, string trand_no, string imei, int cash, string param0, string sign)
		{
			string[] arrayParams = param0.Split(',');
			string nDeviceId = arrayParams[0];
			string nDevice = arrayParams[1];
			string nAppKey = arrayParams[2];

			StringBuilder baseString = new StringBuilder();
			baseString.Append(id)
					.Append(trand_no)
					.Append(cash)
					.Append(param0 == null ? "" : param0)
					.Append(secret_key);

			string sign_local = Md5Hash.Compute(baseString.ToString());

			// 签名验证
			if (sign == sign_local)
			{// 通过
				try
				{
					string nAdOrderId = trand_no;
					DateTime nAdOrderTime = DateTime.Now;
					string nAdDeviceId = imei;
					string nAdId = id;
					string nAdName = "";
					string nAdChannel = "";
					int nIntegral = cash;
					decimal nAppIncome = cash * 2 / 100m;

					AdRecordService.Instance.Create(adPlatform, nAdOrderId, nAdOrderTime, 0, nAdDeviceId, nAdId, nAdName, nAdChannel, nIntegral, nAppIncome, nAppKey, nDevice, nDeviceId);
				}
				catch (Exception<AdRecordExistsExceptionArgs> ex)
				{
					LogManager.GetLogger("IMoPan").Error(trand_no + "磨盘广告记录已存在", ex);
					HttpContext.Response.StatusCode = 403;
				}
				catch (Exception ex)
				{
					LogManager.GetLogger("IMoPan").Error(trand_no + "服务器端错误", ex);
					HttpContext.Response.StatusCode = 500;
				}
			}
			else
			{// 失败
				LogManager.GetLogger("IMoPan").Error(Request.Url + "签名验证不通过");
				HttpContext.Response.StatusCode = 400;
			}

			return new EmptyResult();
		}
    }
}
